#!/usr/bin/python
import sys,time,socket,struct
param = sys.argv[1:]
IP,PACKAGE_SIZE,BUFFER,LOG = param
Mcache = []
Buffer = []
PACKAGE_SIZE = int(PACKAGE_SIZE)
PAYLOAD = PACKAGE_SIZE- 24
log = open(LOG+time.strftime('%Y%m%d%H%M%S')+'.txt','w')
class csnode:
    sNode = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sNode.connect((IP, 50007))
    sNode.send('PLAY')
    while 1:
        data = sNode.recv(PACKAGE_SIZE)
        dataRecv = time.strftime('%H:%M:%S')
        size_recv = len(data)
        if size_recv == PACKAGE_SIZE:
            id,chunk = struct.unpack('24s'+str(PAYLOAD)+'s',data)
	    #Buffer.append(chunk)
            #log.write(str(int(id))+';')
            #log.write(str(size_recv)+';')
            #log.write('recv'+dataRecv+';')
            logdata = str(int(id))+';'
            logdata = logdata+str(size_recv)+';'
            logdata = logdata+'recv'+dataRecv+';'
            #sys.stdout.write(chunk)
	    Buffer.append([logdata,id,chunk])
            if len(Buffer) > int(BUFFER):
                LOGDATA,ID,CHUNK = Buffer.pop(0) 
                sys.stdout.write(CHUNK)
                dataRead = time.strftime('%H:%M:%S')
                log.write(LOGDATA)
                log.write('read'+dataRead+';\r\n')
        else:
            log.write('pacotePerdido;')
            log.write(str(size_recv)+';\r\n')
            break
    while len(Buffer) >0: 
        LOGDATA,ID,CHUNK = Buffer.pop(0) 
        #sys.stdout.write(str(int(ID))+'\r\n')
        sys.stdout.write(CHUNK)
        dataReadBuffer = time.strftime('%H:%M:%S')
        #log.write(str(int(ID))+';')
        log.write(LOGDATA)
        log.write('readBuffer'+dataReadBuffer+';\r\n')
    sNode.close()
node = csnode()
